<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="部门" prop="deptId">
        <el-input
            v-model="queryParams.deptId"
            placeholder="请输入部门"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="风场" prop="farmId">
        <el-input
            v-model="queryParams.farmId"
            placeholder="请输入风场"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['deptFarmMapping:deptFarmMapping:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['deptFarmMapping:deptFarmMapping:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['deptFarmMapping:deptFarmMapping:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="deptFarmMappingList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="序号" type="index" align="center" prop="id"/>
      <el-table-column label="部门" align="center" prop="deptName"/>
      <el-table-column label="风场" align="center" prop="farmName"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['deptFarmMapping:deptFarmMapping:edit']">修改
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['deptFarmMapping:deptFarmMapping:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改部门风场对应关系对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="deptFarmMappingRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="部门" prop="deptId">
          <el-select v-model="form.deptId" placeholder="请选择部门" style="width: 100%">
            <el-option v-for="item in deptOptions" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="风场" prop="farmId">
          <el-select v-model="form.farmId" placeholder="请选择风场" style="width: 100%" disabled>
            <el-option v-for="item in farmOptions" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="DeptFarmMapping">
import {refDebounced} from "@vueuse/core";
import {getFarm, listFarm, updateFarmDept} from "@/api/farm_manage/farm.js";
import {listDept} from "@/api/system/dept.js";

const {proxy} = getCurrentInstance();

const deptFarmMappingList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deptId: null,
    farmId: null,
  },
  rules: {
    deptId: [
      {required: true, message: "部门不能为空", trigger: "blur"}
    ],
    farmId: [
      {required: true, message: "风场不能为空", trigger: "blur"}
    ],
  }
});

const {queryParams, form, rules} = toRefs(data);

const deptAll = ref([])
const farmAll = ref([])
const farmOptions = ref([]);
const deptOptions = ref([]);
const farmNameToIdMap = {};
const deptNameToIdMap = {};

/** 查询部门风场对应关系列表 */
function getList() {
  loading.value = true;

  Promise.all([listFarm(queryParams.value), listDept()])
      .then(([farmResponse, deptResponse]) => {
        farmAll.value = farmResponse.rows;
        deptAll.value = deptResponse.data;

        farmOptions.value = farmAll.value.map(farm => ({
          value: farm.farmId,
          label: farm.farmName
        }));

        deptOptions.value = deptAll.value.map(dept => ({
          value: dept.deptId,
          label: dept.deptName
        }));

        deptFarmMappingList.value = farmAll.value.map(farm => {
          const dept = deptAll.value.find(d => d.deptId === farm.deptId);
          return {
            deptName: dept?.deptName || '',
            farmName: farm.farmName,
            id: farm.farmId
          };
        });
      })

      .finally(() => {
        farmAll.value.forEach(farm => {
          farmNameToIdMap[farm.farmName] = farm.farmId;
        });

        deptAll.value.forEach(dept => {
          deptNameToIdMap[dept.deptName] = dept.deptId;
        });
        loading.value = false;
      });
}

function getDeptFarmMappingInfo() {
  loading.value = true;
  Promise.all([listFarm(), listDept()])
      .then(([farmResponse, deptResponse]) => {
        farmAll.value = farmResponse.rows;
        deptAll.value = deptResponse.data;

        farmOptions.value = farmAll.value.map(farm => ({
          value: farm.farmId,
          label: farm.farmName
        }));

        deptOptions.value = deptAll.value.map(dept => ({
          value: dept.deptId,
          label: dept.deptName
        }));

      })
      .finally(() => {
        loading.value = false;
      });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    deptId: null,
    farmId: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null,
    remark: null
  };
  proxy.resetForm("deptFarmMappingRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  if(queryParams.value.farmId!=null)
  queryParams.value.farmId = farmNameToIdMap[queryParams.value.farmId];
  if(queryParams.value.deptId!=null)
  queryParams.value.deptId = deptNameToIdMap[queryParams.value.deptId];
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  getDeptFarmMappingInfo();
  reset();
  open.value = true;
  title.value = "添加部门风场对应关系";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  getDeptFarmMappingInfo();
  reset();
  const _id = row.id ||  ids.value
    getFarm(_id).then(response => {
      console.log(response.data)
      form.value.deptId = response.data.deptId;
      form.value.farmId = response.data.farmId;
    })
    open.value = true;
    title.value = "修改部门风场对应关系";
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["deptFarmMappingRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateFarmDept(form.value.farmId,form.value.deptId).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除部门风场对应关系编号为"' + _ids + '"的数据项？').then(function () {
    return delDeptFarmMapping(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('deptFarmMapping/deptFarmMapping/export', {
    ...queryParams.value
  }, `deptFarmMapping_${new Date().getTime()}.xlsx`)
}

getList();
</script>
